package pers.zb.center.web.boss.controller.wechat;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.zb.center.common.core.util.JsonUtil;
import pers.zb.center.common.core.vo.AjaxResult;
import pers.zb.center.service.order.api.OrderQueueMessageService;
import pers.zb.center.service.order.entity.OrderInfo;
import pers.zb.center.service.order.enums.OrderSource;
import pers.zb.center.service.order.vo.OrderSync;


/**
 * 微信接口相关功能开发
 * 
 * 操作人: zhoubang 日期：2016年10月22日 下午5:14:46
 *
 */
@Controller
@RequestMapping("/wechat/template")
public class TemplateController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private OrderQueueMessageService orderQueueMessageService;
    
    /**
     * 进入微信模板消息发送页面
     * 
     * 操作人: zhoubang 日期：2016年10月22日 下午5:15:52
     *
     * @param map
     * @return
     */
    @RequestMapping("toTemplateMsgView")
    public String toTemplateMsgView(ModelMap map) {
        map.put("orderSource", OrderSource.values());
        return "/wechat/template/templateMsgSend";
    }

    /**
     * 发送微信模板消息
     * @param openId
     * @return
     */
    @RequestMapping("send")
    @ResponseBody
    public AjaxResult<String> send(String openId, OrderInfo orderInfo) {
        AjaxResult<String> result = new AjaxResult<String>();
        if (StringUtils.isBlank(openId)) {
            result.setCode(10001);
            result.setMsg("openId为空");
            return result;
        }

        try {
            orderInfo.setCreateTime(new Date());
            
            //订单同步对象封装
            OrderSync orderSync = new OrderSync();
            orderSync.setOpenId(openId);
            orderSync.setOrderInfoJson(JsonUtil.toJson(orderInfo));
            logger.debug("订单入库，orderSync：" + JsonUtil.toJson(orderSync));

            orderQueueMessageService.sendOrderSyncQueueMessage(orderSync);
        } catch (Exception e) {
            logger.debug(String.format("订单入库失败，错误信息：%s", e.getMessage()));
            result.setCode(500);
            result.setMsg("订单入库失败，请稍后重试。");
            return result;
        }
        return result;
    }
}
